package top.laoshuzi.common.mvp.factory;

import android.support.annotation.Nullable;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import top.laoshuzi.common.mvp.presenter.Presenter;
import top.laoshuzi.common.mvp.presenter.Presenter.OnLifecycleListener;

public enum PresenterStorage {

    INSTANCE;

    private HashMap<String, Presenter> idToPresenter = new HashMap<>();
    private HashMap<Presenter, String> presenterToId = new HashMap<>();

    public void add(Presenter... presenters) {
        for (final Presenter presenter : presenters) {
            String id = presenter.getClass().getSimpleName() + "/" + System.nanoTime() + "/" + (int) (Math.random() * Integer.MAX_VALUE);
            idToPresenter.put(id, presenter);
            presenterToId.put(presenter, id);
            presenter.addOnLifecycleListener(new OnLifecycleListener() {
                @Override
                public void onCreate() {

                }

                @Override
                public void onDestroy() {
                    idToPresenter.remove(presenterToId.remove(presenter));
                }
            });
        }
    }

    public void add(List<? extends Presenter> presenters) {
        for (final Presenter presenter : presenters) {
            String id = presenter.getClass().getSimpleName() + "/" + System.nanoTime() + "/" + (int) (Math.random() * Integer.MAX_VALUE);
            idToPresenter.put(id, presenter);
            presenterToId.put(presenter, id);
            presenter.addOnLifecycleListener(new OnLifecycleListener() {
                @Override
                public void onCreate() {

                }

                @Override
                public void onDestroy() {
                    idToPresenter.remove(presenterToId.remove(presenter));
                }
            });
        }
    }

    public List<? extends Presenter> getPresenter(@Nullable String[] ids) {
        List<Presenter> presenters = null;
        for (String id : ids) {
            Presenter presenter = idToPresenter.get(id);
            if (presenter != null) {
                if (null == presenters) {
                    presenters = new ArrayList<>();
                }
                presenters.add(presenter);
            }
        }
        return presenters;
    }

    public String getId(Presenter presenter) {
        return presenterToId.get(presenter);
    }

    public void clear() {
        idToPresenter.clear();
        presenterToId.clear();
    }
}
